﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

using System.Xml;
using System.Xml.Serialization;

using DotSpatial.Topology;
using DotSpatial.Data;
using DotSpatial.Symbology;
using DotSpatial.Symbology.Forms;
using DotSpatial.Controls;




namespace HaGisPack
{
    public class LayerSystem : SubSystem
    {

        public LayerSystem(GisManager m)
            : base(m)
        {
 
        }

      
        //public event LayerAddHandler LayerAdded;


         [field: NonSerialized]
        public event GisHandler LayerChanged;


         Dictionary<string, FLayer> m_Layers;



       /// <summary>
       /// 取得当前的所有图层，这里取得的图层，严禁修改其中的值
       /// </summary>
         public Dictionary<string, FLayer> Layers
         {
             get { return m_Layers; }
            
         }


        /// <summary>
        /// 主活动层级
        /// </summary>
        FLayer m_CurrentLayer;

        /// <summary>
        /// 取得当前图层
        /// </summary>
        public FLayer CurrentLayer
        {
            get { return m_CurrentLayer; }
            
        }


        /// <summary>
        /// 设置当前图层
        /// </summary>
        /// <param name="lname"></param>
        public void SetCurrentLayer(string lname)
        {
            if (this.m_Layers.ContainsKey(lname))
            {

                this.m_CurrentLayer = this.m_Layers[lname];
            }
            else  //复合层
            {
                foreach (FLayer item in m_Layers.Values)
                {
                    FCompoundLayer fcl = item as FCompoundLayer;
                    if (fcl != null)
                    {
                        if (fcl.IsChildExist(lname))
                        {
                            this.m_CurrentLayer = fcl.Childs[lname];
                        }

                    }

                }
            }
 
        }



        #region 针对图层的操作


        /// <summary>
        /// 当图层代表需要重绘时，调用此函数
        /// </summary>
        public void declareLayerChanged()
        {
            if (LayerChanged != null)
            {
                LayerChanged();
            }

 
        }

        public void AddLayer(FLayer layer)
        {
            layer.ParentManger = this.Parent;

            m_Layers.Add(layer.Id, layer);


            layer.BuildEntity();


            this.Parent.CurrentMap.Invalidate();

            this.declareLayerChanged();
           

        }



        public void RemoveLayer(string id)
        {
            if (!this.Layers .ContainsKey (id))
            {
                return;
            }


            IMapLayer l = this.GetLayer(id).ILayer ;

            this.Parent.CurrentMap.Layers.Remove(l);

            this.Layers.Remove(id);


            this.declareLayerChanged();

        }


        public void RemoveAllLayer()
        {

            this.Layers.Clear();

            this.Parent.CurrentMap.ClearLayers();


            this.declareLayerChanged();


        }



        public FLayer GetLayer(string lname)
        {

            if (m_Layers.ContainsKey(lname))
            {

                return m_Layers[lname];
            }
            else
            {

                foreach (FLayer item in m_Layers.Values)
                {
                    FCompoundLayer fcl = item as FCompoundLayer;
                    if (fcl != null)
                    {
                        if (fcl.IsChildExist(lname))
                        {
                            return fcl.GetChild(lname);
                        }

                    }

                }
                return null;
            }

        }




        public bool SaveLayer(string lname,string path)
        {
            return true;
 
        }



        public bool OpenLayer(string lname,string path)
        {
            return true;
        }




        #endregion




        public IFeatureLayer GetFeatureLayer(string lname)
        {

            FLayer flayer = this.GetLayer(lname);

            if (flayer != null)
            {
                FShapeLayer f = flayer as FShapeLayer;

                if (f != null)
                {
                    return f.IFLayer;

                }
                else
                {
                    return null;
                }

            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 返回所有的可供编辑的图层featurelayer
        /// </summary>
        /// <returns></returns>
        public List<IFeatureLayer> GetEditableFeatureLayers()
        {
            List<IFeatureLayer> layers = new List<IFeatureLayer>();

            foreach (FLayer item in m_Layers.Values)
            {
                if (item.LayerType == FLayerType.CompoundLayer)  //如果是复合层
                {
                    foreach (FLayer lay in (item as FCompoundLayer).Childs.Values)
                    {
                        if (item.BShapeEditable)
                        {
                            IFeatureLayer ifl = lay.ILayer as IFeatureLayer;
                            layers.Add(ifl);
                        }
                    }
                }
                else
                {
                    if (item.BShapeEditable)
                    {
                        IFeatureLayer ifl = item.ILayer as IFeatureLayer;
                        layers.Add(ifl);
                    }
                }
            }



            return layers;


        }


        public List<FLayer> GetEditableLayers()
        {

            List<FLayer> layers = new List<FLayer>();


            foreach (FLayer item in m_Layers.Values)
            {
                if (item.BShapeEditable)
                {

                    layers.Add(item);

                }


            }



            return layers;


        }


        public List<FShape> GetSelectedShps()
        {
            List<IFeature> selectedFeatures = new List<IFeature>();

            foreach (HaGisPack.FLayer layer in this.Layers.Values)
            {
                selectedFeatures.AddRange((layer.ILayer as DotSpatial.Symbology.IFeatureLayer).Selection.ToFeatureList());

            }
            List<FShape> selectedshapes = new List<FShape>();  // 自定义的shp，所选的


            foreach (HaGisPack.FShapeLayer flayer in this.Layers.Values)
            {
                foreach (HaGisPack.FShape fshp in flayer.Shapes.Values)
                {

                    foreach (DotSpatial.Data.Feature feature in selectedFeatures)
                    {

                        if (fshp.Id == (string)feature.DataRow["id"])
                        {
                            selectedshapes.Add(fshp);
                        }

                    }

                }
            }

            return selectedshapes;
        }


        #region  关于shape的辅助函数


        /// <summary>
        /// 添加图形到指定的图层，其中图形本身必须包含有对应的父亲定义
        /// </summary>
        /// <param name="shp"></param>
        public void AddShape(FShape shp)
        {

            string ln = shp.LayerName;
            if (ln != "")
            {

                FShapeLayer lay = (FShapeLayer)this.GetLayer(ln); //直接用下面一句不就行了，干嘛多此一举再求一次！！！
                //lay = (FShapeLayer)this.CurrentLayer;
                if (lay != null)
                {
                    lay.AddShape(shp);

                }

            }
            
        }

        public void ChangeShape(FShape shp)
        {
            string ln = shp.LayerName;
            if (ln != "")
            {

                FShapeLayer lay = (FShapeLayer)this.GetLayer(ln); //直接用下面一句不就行了，干嘛多此一举再求一次！！！
                //lay = (FShapeLayer)this.CurrentLayer;
                if (lay != null)
                {
                    lay.ModifyShape(shp);

                }

            }
 
        }

        public void RemoveShape(FShape shp)
        {
            string ln = shp.LayerName;
            if (ln != "")
            {

                FShapeLayer lay = (FShapeLayer)this.GetLayer(ln); //直接用下面一句不就行了，干嘛多此一举再求一次！！！
                //lay = (FShapeLayer)this.CurrentLayer;
                if (lay != null)
                {
                    lay.RemoveShape(shp.Id);

                }

            }
        }
        
        #endregion


        #region IProj 成员

        public bool SaveProj()
        {

           bool b=false ;

           foreach (FLayer item in m_Layers.Values)
           {
               if (item.LayerType == FLayerType.CompoundLayer)
               {
                   foreach (FLayer lay in (item as FCompoundLayer).Childs.Values)
                   {
                       lay.SaveEntity();
                   }
               }
               else
               {
                   item.SaveEntity();
               }

           }

           b = FFileHelper.SaveToBinary(this.Parent.AbsProjPathName, this.m_Layers);

           
           return b;


        }


        public bool OpenProj()

        {
            if (!File.Exists (this .Parent .AbsProjPathName ))
            {
                return false;
            }

            bool b=false ;
           this.m_Layers =(Dictionary <string, FLayer>)  FFileHelper.OpenFromBinary(this.Parent .AbsProjPathName,ref b);
           if (b)
           {
               foreach (FLayer item in m_Layers.Values)
               {
                   item.ParentManger = this.Parent;

                   if (item.LayerType == FLayerType.CompoundLayer)
                   {
                       foreach (FLayer lay in (item as FCompoundLayer).Childs.Values)
                       {
                           lay.ParentManger = this.Parent;
                           
                           lay.LoadEntity();
                           lay.BuildEntity();
                       }
                   }
                   else
                   {
                       item.LoadEntity();

                       item.BuildEntity();
                   }

               }
           }

           this.declareLayerChanged();

           return b;


        }

        public bool NewProj()
        {
            m_Layers = new Dictionary<string, FLayer>();
            //this.Parent.SaveProj();
            return true;

        }

        public bool SaveAsProj()
        {
            throw new NotImplementedException();
        }

        public bool CloseProj()
        {

            if (m_Layers !=null )
            {
                foreach (FLayer lay in this.m_Layers.Values)
                {
                    //单个图层要关闭一些参数                   
                    lay.CloseLayer();                     
                }

                //清空
                m_Layers.Clear();

                m_Layers = null;
                
            }



            this.Parent.CurrentMap.Layers.Clear();
            //this.Parent.CurrentMap.MapFrame.Invalidate();

            //tree控件刷新
            this.declareLayerChanged();

            return true;
        }

        #endregion
    }
}
